package com.gexin.controller.system.freeacquire;

import com.gexin.common.model.ApiResponse;
import com.gexin.core.web.SystemBaseController;
import com.gexin.model.activity.FreeAcquire;
import com.gexin.service.freeacquire.FreeAcquireService;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 免费申领服务
 */
@ControllerBind(controllerKey = "/system/activity/freeAcquire", viewPath = "WEB-INF/system/freeacquire")
public class FreeAcquireController  extends SystemBaseController {
    public static final FreeAcquireService freeAcquireService = new FreeAcquireService();

    public void index() {
        if (isAjax()) {
            Map map = new HashMap();
            Page<FreeAcquire> list = freeAcquireService.findList(getpage(), getpageSize());
            FreeAcquire FreeAcquire = freeAcquireService.freeAcquire();
            if(null!=FreeAcquire){
                String activityId = FreeAcquire.getActivityId();
                map.put("freeAcquirePage", list);
                map.put("activityId", activityId);
            }
            renderJson(map);
            return;

        }
        render("free_acquire.html");
    }

    public void addProductWithFreeAcquire() {
        String productId = getPara("product_id");
        String activityId = getPara("activity_id");
        Page<FreeAcquire> freeAcquirePage = freeAcquireService.findList(getpage(), getpageSize());
        List<FreeAcquire> list = freeAcquirePage.getList();
        boolean flag = list.stream().anyMatch(freeAcquire -> StringUtils.isNotBlank
                (freeAcquire.getProductId())&&freeAcquire.getProductId().equals(productId));
        if(true==flag){
            fail("产品已存在，请勿重复添加");
            return;
        }
        Boolean addProductWithFreeAcquire = freeAcquireService.addProductWithFreeAcquire(productId, activityId);
        if (null == addProductWithFreeAcquire) {
            renderJson(new ApiResponse(false,"产品id不存在,请检查是否正确后重试"));
            return;
        }
        renderJson(new ApiResponse(addProductWithFreeAcquire, addProductWithFreeAcquire ? "添加成功!" : "添加失败!"));
        return;
    }

    public void delete(){
        String freeAcitivtyId = getPara("id");
        boolean delete = FreeAcquire.dao.deleteById(freeAcitivtyId);
        renderJson(new ApiResponse(delete,delete ? "删除成功!" : "删除失败!"));
        return;
    }

    public void tree(){
        List checkProduct = freeAcquireService.findCheckProduct();
        renderJson(checkProduct);
    }








}
